const jwt = require('jsonwebtoken');
const HttpError = require('../models/errorModel')

const authMiddleware = async (req, res, next) => {
    const Authorization = req.headers.Authorization || req.headers.authorization
    //请求头部授权
    if (Authorization && Authorization.startsWith('Bearer')) {
        //如果授权信息存在且以bearer开头
        const token = Authorization.split(' ')[1];
        //从请求头部中取出token
        jwt.verify(token, process.env.JWT_SECRET, (err, info) => {
            //使用jwt对token进行验证,验证结果放在info变量里
            if (err) {
                //如果出现异常
                return next(new HttpError('Unauthorized. Invalid token', 403));
            }//则返回错误提示Unauthorized. Invalid token
            req.user = info;
            next();
        })//如果验证成功，赋值给req.user，执行下一步操作
    } else {
        return next(new HttpError('Unauthorized. No token provided', 402));
    }//如果没有提供令牌，则返回错误提示Unauthorized. No token provided
}

module.exports = authMiddleware;